<?php
class Controller_Storage_DFoverseas extends Controller_Abstract
{
	function actionAssignList()
	{
		$this->_view['title'] = '配货单列表';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$condition = Helper_BSS_Normal::buildCondition();
		$condition['warehouse_id'] = Warehouse::getWarehouseIdsByType('dafang');
		$condition['trash_status'] = Q::ini('custom_flag/sales_order_trash_status/normal/value');
		$condition['order_status'][Q::ini('custom_flag/sales_order_handle_status/checkout/value')] = Q::ini('custom_flag/sales_order_handle_status/checkout/value');
		$result = Sales_Order::search($condition, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$sales_order = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Storage::DFOverseas/AssignList', $condition));
			$this->_view['page'] = $page->getPage();
			Sales_Order_Notes::getOrderNotes($sales_order);
			Sales_Order_Item_Attribute::getSalesOrderItemAttr($sales_order);
			Sales_Order::checkWarning($sales_order);
			$this->_view['sales_order'] = $sales_order;
		}
	}
	
	function actionAssignAll()
	{
		$this->_view['title'] = '全部配货';
		$condition['warehouse_id'] = Warehouse::getWarehouseIdsByType('dafang');
		$condition['trash_status'] = Q::ini('custom_flag/sales_order_trash_status/normal/value');
		$condition['order_status'][Q::ini('custom_flag/sales_order_handle_status/checkout/value')] = Q::ini('custom_flag/sales_order_handle_status/checkout/value');
		$where = Sales_Order::buildSearchWhere($condition);
		$sales_order_ids = QDB::getConn()->execute('select id from sales_order where ' . $where . ' order by make_time asc')->fetchCol('id');
		$result = Sales_Order::changeHandleStatusFromCheckoutToAssigned($sales_order_ids);
		if ($result['ack'] == SUCCESS)
		{
			return $this->_redirectMessage('配货成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
		}
		else
		{
			return $this->_redirectMessage('配货部分失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
		}
	}
	
	function actionAssignByChecked()
	{
		$this->_view['title'] = '按勾选配货';
		if (isset($_GET['ids']) && $_GET['ids'])
		{
			$sales_order_ids = explode(',', $_GET['ids']);
			$result = Sales_Order::changeHandleStatusFromCheckoutToAssigned($sales_order_ids);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('配货成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('配货部分失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
	}
	
	function actionOperateList()
	{
		$this->_view['title'] = '处理单列表';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 20;
		$warehouse = Warehouse::find('type=? and status=?', 'dafang', true)->asArray()->getAll();
		$shipping_method = Shipping_Method::getTreeShippingMethod();
		$warehouse_id = array();
		foreach ($warehouse as $w)
		{
			$warehouse_id[] = $w['id'];
			if ( ! empty($shipping_method[$w['code']]))
			{
				$shipping_method_arr[$w['code']] = $shipping_method[$w['code']];
			}
		}
		$this->_view['shipping_method'] = $shipping_method_arr;
		$this->_view['warehouse'] = $warehouse;
		$this->_view['shop'] = Shop::getActiveShop();
		$df_order_type = array();
		foreach (Q::ini('custom_flag/DF_order_type') as $wo)
		{
			$df_order_type[$wo['wcode']][] = $wo;
		}
		$this->_view['df_order_type'] = $df_order_type;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$url_arr['trash_status'] = Q::ini('custom_flag/sales_order_trash_status/normal/value');
		$url_arr['overseas_order_operate_status'] = true;
		$url_arr['warehouse_id'] = empty($url_arr['warehouse_id']) ? $warehouse_id : $url_arr['warehouse_id'];
		$result = Sales_Order::search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$sales_order = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Storage::DFOverseas/OperateList', $url_arr));
			$this->_view['page'] = $page->getPage();
			Sales_Order_Notes::getOrderNotes($sales_order);
			Sales_Order_Item_Attribute::getSalesOrderItemAttr($sales_order);
			Sales_Order::checkWarning($sales_order);
			$this->_view['sales_order'] = $sales_order;
		}
	}
	
	function actionReturnList()
	{
		$this->_view['title'] = '销售退货单列表';
		$shop = Shop::getActiveShop();
		$this->_view['shop'] = $shop;
		$this->_view['warehouse'] = Warehouse::find('type=? and status=?', 'dafang', true)->asArray()->getAll();
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 0;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$url_arr['warehouse_id'] = Warehouse::getWarehouseIdsByType('df');
		$result = Sales_Return::search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$sales_return = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Storage::DFoverseas/ReturnList', $url_arr));
			$this->_view['page'] = $page->getPage();
			Sales_Order_Notes::getOrderNotes($sales_return);
			$this->_view['sales_return'] = $sales_return;
		}
	}
	
	function actionReturnInfo()
	{
		$this->_view['title'] = '退货详细信息';
		if ($_GET['id'])
		{
			$return = Sales_Return::find('id=?', $_GET['id'])->asArray()->getOne();
			$sales_order_id = $return['sales_order_id'];
			$return['item'] = Sales_return_item::find('sales_return_id=?', $return['id'])
				->joinLeft('product_basic', 'number as product_number, name as product_name', 'product_basic.id=sales_return_item.product_basic_id')
				->asArray()->getAll();
			$sales_order = Sales_Order::find('sales_order.id=?', $sales_order_id)->asArray()->getOne();
			$shop = Shop::find('id=?', $sales_order['shop_id'])->asArray()->getOne();
			$this->_view['shop'] = $shop;
			$this->_view['sales_return'] = $return;
			$this->_view['sales_order'] = $sales_order;
			$this->_view['return'] = $return['item'];
		}
	}
	
	function actionReturnStoraged()
	{
		$this->_view['title'] = '退货单审核入库';
		$sales_return_ids = explode(',', $_GET['ids']);
		if ($sales_return_ids)
		{
			$result = Sales_Return::storageAudit($sales_return_ids);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('审核成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('部分审核失败', $result['message'], $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
	}
	
	function actionMultiHold()
	{
		$this->_view['title'] = '批量仓库滞留';
		if (isset($_POST['ids']) && $_POST['ids'])
		{
			$ids = explode(',', $_POST['ids']);
			$result = Sales_Order::changeHandleStatusToStorageHold($ids);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('仓库滞留成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('仓库滞留失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
	}
	
	function actionMultiToCheckout()
	{
		$this->_view['title'] = '返回销售确认';
		if (isset($_POST['ids']) && $_POST['ids'])
		{
			$ids = explode(',', $_POST['ids']);
			$result = Sales_Order::changeHandleStatusFromStorageHoldToCheckout($ids);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('销售确认成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('销售确认失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
	}
	
	function actionMultiToSalesHold()
	{
		$this->_view['title'] = '返回销售滞留';
		if (isset($_POST['id']) && $_POST['id'])
		{
			$ids = explode(',', $_POST['id']);
			$result = Sales_Order::changeHandleStatusFromStorageHoldToSalesHold($ids, $_POST['notes_content']);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('销售滞留成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('销售滞留失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
	}
	
	function actionExpressDF()
	{
		$this->_view['title'] = '同步DF';
		$sales_order_ids = explode(',', $_POST['ids']);
		if ($sales_order_ids)
		{
			if (! empty($_POST['order_type']))
			{
				$result = Sales_Order::expressDF($sales_order_ids, $_POST['order_type'], $_POST['is_repeat']);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('同步成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
				}
				elseif ($result['ack'] == PARTIAL_FAILURE)
				{
					return $this->_redirectMessage('同步部分失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('同步失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('没有选择同步的订单方式', '请检查提交信息', $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
		else
		{
			return $this->_redirectMessage('没有符合条件订单', '请检查订单是否符合条件', $_SERVER['HTTP_REFERER'], FAILURE);
		}
		
	}
	
	function actionAddNotes()
	{
		$this->_view['title'] = '添加仓库备注';
		if ($this->_context->isPOST())
		{
			$result = Sales_Order_Notes::create($_POST['id'], $_POST['notes_content'], Q::ini('custom_flag/sales_order_notes_type/warehouse/value'));
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('添加成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('添加失败', $result['message'], $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
		return $this->_redirectMessage('操作失败', '不是提交动作', $_SERVER['HTTP_REFERER'], FAILURE);
	}
	
	function actionPrintReceivingTable()
	{
		$this->_view['title'] = '打印收货单';
		$ids = explode(',', $_GET['ids']);
		if ($ids)
		{
			$instore = DF_Overseas_Instore::find('df_overseas_instore.id in (?)', $ids)
				->joinLeft('user as a', 'name as make_user_name', 'a.id = df_overseas_instore.make_user_id')
				->joinLeft('user as b', 'name as confirmed_user_name', 'b.id = df_overseas_instore.confirmed_user_id')
				->joinLeft('user as c', 'name as storage_audit_user_name', 'c.id = df_overseas_instore.storage_audit_user_id')
				->asArray()->getAll();
			foreach ($instore as &$i)
			{
				$item = DF_Overseas_Instore_Item::find('df_overseas_instore_item.df_overseas_instore_id=? and df_overseas_instore_item.quantity>0', $i['id'])
					->joinLeft('product_basic', 'number as product_number, name as product_name', 'product_basic.id=df_overseas_instore_item.product_basic_id')
					->joinLeft('product_warehouse', 'shelf_position, sold_quantity', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=' . $i['warehouse_id'])
					->order('product_basic.number asc')->asArray()->getAll();
				$i['item'] = $item;
			}
			unset($i);
			$this->_view['instore'] = $instore;
		}
	}
	
	function actionPrintProductBarcode()
	{
		$this->_view['title'] = '打印产品条形码';
		$ids = explode(',', $_GET['ids']);
		if ($ids)
		{
			$instore = DF_Overseas_Instore::find('id in (?)', $ids)->asArray()->getAll();
			$item = array();
			foreach ($instore as $i)
			{
				$instore_item = DF_Overseas_Instore_Item::find('df_overseas_instore_item.df_overseas_instore_id=?', $i['id'])
					->joinLeft('product_basic', '', 'product_basic.id=df_overseas_instore_item.product_basic_id')
					->joinLeft('product_warehouse', '', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=' . $i['warehouse_id'])
					->joinLeft('product_material','', 'product_material.id=product_warehouse.product_material_id')
					->setColumns('product_basic.number, product_warehouse.shelf_position, product_warehouse.product_feature, df_overseas_instore_item.quantity, product_material.number as material_number')
					->asArray()->getAll();
				$item = array_merge($instore_item, $item);
			}
			$item = Helper_BSS_Array::SortByValue($item, 'number', 'asc');
			OLM_Barcode::productNumber($item);
			exit;
		}
	}

	function actionOutList()
	{
		$this->_view['title'] = '出库单列表';
		$this->_view['shop'] = Shop::getActiveShop();
		$warehouse = Warehouse::find('type=? and status=?', 'dafang', true)->asArray()->getAll();
		$shipping_method = Shipping_Method::getTreeShippingMethod();
		$warehouse_id = array();
		foreach ($warehouse as $w)
		{
			$warehouse_id[] = $w['id'];
			if ( ! empty($shipping_method[$w['code']]))
			{
				$shipping_method_arr[$w['code']] = $shipping_method[$w['code']];
			}
		}
		$this->_view['shipping_method'] = $shipping_method_arr;
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$url_arr['trash_status'] = Q::ini('custom_flag/sales_order_trash_status/normal/value');
		$url_arr['order_status'][Q::ini('custom_flag/sales_order_handle_status/shipped/value')] = Q::ini('custom_flag/sales_order_handle_status/shipped/value');
		$url_arr['order_status'][Q::ini('custom_flag/sales_order_handle_status/return/value')] = Q::ini('custom_flag/sales_order_handle_status/return/value');
		$url_arr['shipping_status'] = Q::ini('custom_flag/sales_order_shipping_status/shipped/value');
		$url_arr['warehouse_id'] = $warehouse_id;
		$result = Sales_Order::search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$order = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Storage::DFOverseas/OutList', $url_arr));
			$this->_view['page'] = $page->getPage();
			$where = Sales_Order::buildSearchWhere($url_arr);
			$postage = QDB::getConn()->execute('select sum(weight) as weight, sum(sales_order.postage) as postage_amount, sum(sales_order.postage*sales_order.postage_currency_rate) as postage_amount_cny, currency.code from sales_order left join sales_order_customer_info on sales_order_customer_info.sales_order_id=sales_order.id left join currency on currency.id=sales_order.postage_currency_id where ' . $where . ' and sales_order.postage_currency_id>0 group by sales_order.postage_currency_id')->fetchAll();
			$this->_view['postage'] = $postage;
			$this->_view['order'] = $order;
		}
	}
	
	function actionPurchaseList()
	{
		$this->_view['title'] = '采购单列表';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 0;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$user = Purchase_Order::getUser();
		$this->_view['user'] = $user['data'];
		$warehouse = Warehouse::find('type=? and status=?', 'dafang', true)->asArray()->getAll();
		$this->_view['warehouse'] = $warehouse;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$url_arr['type'] = Q::ini('custom_flag/purchase_order_type/order/value');
		if (empty($url_arr['warehouse_id']))
		{
			foreach ($warehouse as $w)
			{
				$url_arr['warehouse_id'][] = $w['id'];
			}
		}
		if (empty($url_arr['purchase_order_status']))
		{
			$url_arr['purchase_order_status'] = array(
				Q::ini('custom_flag/purchase_order_status/purchased/value') => Q::ini('custom_flag/purchase_order_status/purchased/value'), 
				Q::ini('custom_flag/purchase_order_status/arrived/value') => Q::ini('custom_flag/purchase_order_status/arrived/value'),
				Q::ini('custom_flag/purchase_order_status/send/value') => Q::ini('custom_flag/purchase_order_status/send/value'),
				Q::ini('custom_flag/purchase_order_status/storaged/value') => Q::ini('custom_flag/purchase_order_status/storaged/value'),
			);
			$condition = $url_arr;
			unset($url_arr['purchase_order_status']);
		}
		else
		{
			$condition = $url_arr;
		}
		$result = Purchase_Order::search($condition, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$this->_view['purchase_order'] = $result['data'];
			$page = new Helper_BSS_Page($result['pagination'], url('Storage::DFOverseas/PurchaseList', $url_arr));
			$this->_view['page'] = $page->getPage();
		}
	}
	
	function actionDetail()
	{
		$this->_view['title'] = '详细';
		$material = Product_Material::find()->asArray()->getAll();
		$this->_view['material'] = $material;
		if (! empty($_GET['id']))
		{
			$purchase_order = Purchase_Order::find('purchase_order.id=?', $_GET['id'])
				->joinLeft('warehouse', 'warehouse.name as warehouse_name', 'warehouse.id=purchase_order.warehouse_id')
				->joinLeft('user', 'name as purchase_user_name', 'user.id=purchase_order.purchase_user_id')
				->asArray()->getOne();
			if ($purchase_order)
			{
				$where = 'purchase_order_item.purchase_order_id=' . $_GET['id'];
				if (isset($_GET['show_all']) && $_GET['show_all'] == 0)
				{
					$where .= ' and purchase_order_item.actual_quantity>0';
				}
				$item = Purchase_Order_Item::find($where)
					->joinLeft('product_basic', 'number as product_number, name as product_name, weight, declared_value, declared_name_cn, declared_name_en', 'product_basic.id=purchase_order_item.product_basic_id')
					->joinLeft('product_warehouse', 'id as product_warehouse_id, actual_quantity as product_warehouse_actual_quantity, shelf_position, product_feature, tag', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=' . $purchase_order['warehouse_id'])
					->joinLeft('product_material', 'id as product_material_id, number as material_number, name as material_name', 'product_material.id=product_warehouse.product_material_id')
					->order('product_basic.number asc')->asArray()->getAll();
				Helper_BSS_Normal::getProductImgUrl($item, 'product_number');
				$this->_view['purchase_order'] = $purchase_order;
				$this->_view['item'] = $item;
			}
		}
	}
	
	function actionReturnPurchased()
	{
		$this->_view['title'] = '返审已采购';
		$ids = explode(',', $_GET['ids']);
		if ($ids)
		{
			$result = Purchase_Order::returnPurchased($ids);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('成功返回已采购', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('部分返回已采购失败' ,$result['message'], $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
	}
	
	function actionConfirmPurchaseToArrive()
	{
		$this->_view['title'] = '确认已到仓';
		if (! empty($_GET['ids']))
		{
			$ids = explode(',', $_GET['ids']);
			$message = array();
			foreach ($ids as $id)
			{
				$result = Purchase_Order::auditWarehoused($id);
				if ($result['ack'] == FAILURE)
				{
					$message[] = $result['message'];
				}
			}
			if ($message)
			{
				return $this->_redirectMessage('确认到仓部分失败', implode("\n", $message), $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('确认到仓成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('确认到仓失败', '提交信息有误，请重试！', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionConfirmArriveToSend()
	{
		$this->_view['title'] = '确认发送';
		if (! empty($_GET['ids']))
		{
			$ids = explode(',', $_GET['ids']);
			$result = Purchase_Order::auditSend($ids);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('发送成功', '正在返回..', url('Storage::DFOverseas/PurchaseList'), $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('发送部分失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('发送失败', '提交信息有误，请重试！', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionAuditStorage()
	{
		$this->_view['title'] = '审核入库';
		if (! empty($_GET['ids']))
		{
			$ids = explode(',', $_GET['ids']);
			$result = Purchase_Order::auditStorage($ids);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('审核成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
			else
			{
				return $this->_redirectMessage('部分审核失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('审核入库失败', '提交信息有误，请重试！', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionPrintPurchaseReceivingTable()
	{
		$this->_view['title'] = '打印收货单';
		$ids = explode(',', $_GET['ids']);
		if ($ids)
		{
			$purchase_order = Purchase_Order::find('purchase_order.id in (?)', $ids)
				->joinLeft('warehouse', 'name as warehouse_name', 'warehouse.id=purchase_order.warehouse_id')
				->joinLeft('user as a', 'name as make_user_name', 'a.id = purchase_order.make_user_id')
				->joinLeft('user as b', 'name as purchase_user_name', 'b.id = purchase_order.purchase_user_id')
				->joinLeft('user as c', 'name as purchase_audit_user_name', 'c.id = purchase_order.purchase_audit_user_id')
				->joinLeft('user as d', 'name as storage_audit_user_name', 'd.id = purchase_order.storage_audit_user_id')
				->joinLeft('user as e', 'name as complete_user_name', 'e.id = purchase_order.complete_user_id')
				->joinLeft('user as f', 'name as send_user_name', 'f.id = purchase_order.send_user_id')
				->joinLeft('user as g', 'name as arrive_user_name', 'g.id = purchase_order.arrive_user_id')
				->asArray()->getAll();
			foreach ($purchase_order as &$p)
			{
				$item = Purchase_Order_Item::find('purchase_order_item.purchase_order_id=? and purchase_order_item.actual_quantity>0', $p['id'])
					->joinLeft('product_basic', 'number as product_number, name as product_name', 'product_basic.id=purchase_order_item.product_basic_id')
					->joinLeft('product_warehouse', 'shelf_position, sold_quantity', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=' . $p['warehouse_id'])
					->order('product_basic.number asc')->asArray()->getAll();
				$p['item'] = $item;
			}
			unset($p);
			$this->_view['purchase_order'] = $purchase_order;
		}
	}
	
	function actionPrintPurchaseProductBarcode()
	{
		$this->_view['title'] = '打印产品条形码';
		$ids = explode(',', $_GET['ids']);
		if ($ids)
		{
			$purchase_order = Purchase_Order::find('id in (?)', $ids)->asArray()->getAll();
			$item = array();
			foreach ($purchase_order as $o)
			{
				$purchase_order_item = Purchase_Order_Item::find('purchase_order_item.purchase_order_id=?', $o['id'])
					->joinLeft('product_basic', '', 'product_basic.id=purchase_order_item.product_basic_id')
					->joinLeft('product_warehouse', '', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=' . $o['warehouse_id'])
					->joinLeft('product_material','', 'product_material.id=product_warehouse.product_material_id')
					->setColumns('product_basic.number, product_warehouse.shelf_position, product_warehouse.product_feature, purchase_order_item.actual_quantity as quantity, product_material.number as material_number')
					->asArray()->getAll();
				$item = array_merge($purchase_order_item, $item);
			}
			OLM_Barcode::productNumber($item);
			exit;
		}
	}
	
	function actionActualQuantitySave()
	{
		$this->_view['title'] = '采购实际数量保存（ajax）';
		if (! empty($_REQUEST['purchase_order_item_id']))
		{
			$purchase_order_item = Purchase_Order_Item::find('id=?', $_REQUEST['purchase_order_item_id'])->getOne();
			if ($purchase_order_item['id'] && $purchase_order_item['audit_flag'] == Q::ini('custom_flag/purchase_order_item_audit_flag/unaudited/value'))
			{
				$purchase_actual_quantity = (int)trim($_REQUEST['purchase_actual_quantity']);
				if ($purchase_actual_quantity <= $purchase_order_item['budget_quantity'])
				{
					$purchase_order = Purchase_Order::find('id=?', $purchase_order_item['purchase_order_id'])->asArray()->getOne();
					if ($purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/arrived/value'))
					{
						Product_Warehouse::purchaseActualQuantityDecrease(0, $purchase_order_item['product_basic_id'], $purchase_order['warehouse_id'], (int)$purchase_order_item['actual_quantity']);
						Product_Warehouse::purchaseActualQuantityIncrease(0, $purchase_order_item['product_basic_id'], $purchase_order['warehouse_id'], (int)$purchase_actual_quantity);
					}
					if ($purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/purchased/value') || $purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/arrived/value'))
					{
						Product_Warehouse::purchaseQuantityDecrease(0, $purchase_order_item['product_basic_id'], $purchase_order['warehouse_id'], (int)$purchase_order_item['actual_quantity']);
					}
					$purchase_order_item->actual_quantity = (int)($purchase_actual_quantity);
					$purchase_order_item->save();
					Product_Warehouse::purchaseQuantityIncrease(0, $purchase_order_item['product_basic_id'], $purchase_order['warehouse_id'], (int)$purchase_order_item['actual_quantity']);
					Purchase_Order::updateOrder($purchase_order['id']);
					exit;
				}
				else
				{
					echo json_encode('实际数不能大于预计数！');exit;
				}
			}
			else
			{
				echo json_encode('item信息不存在或已审核！');exit;
			}
		}
		else
		{
			echo json_encode('缺失数据！');exit;
		}
	}
	
	function actionOutputDFInstoreTpl()
	{
		$this->_view['title'] = '导出达方快速装箱模板';
		 if (isset($_GET['ids']))
		{
			$ids = explode(',', $_GET['ids']);
			$product = Purchase_Order_Item::find('purchase_order_item.purchase_order_id in (?)', $ids)
				->joinLeft('product_basic', 'product_basic.*', 'purchase_order_item.product_basic_id=product_basic.id')
				->asArray()->getAll();
			include Q::ini('custom_system/lib_dir').'PHPExcel.php';
			$phpexcel = new PHPExcel();
			$phpexcel->getProperties()->setCreator(Q::ini('custom_system/system_name') . Q::ini('custom_system/version'));
			$phpexcel->getProperties()->setLastModifiedBy(Q::ini('custom_system/system_name') . Q::ini('custom_system/version'));
			$phpexcel->getProperties()->setTitle("快速装箱模板");
			$phpexcel->getProperties()->setSubject('快速装箱模板');
			$phpexcel->getProperties()->setDescription('快速装箱模板-运营系统');
			$phpexcel->getProperties()->setKeywords('快速装箱模板');
			$phpexcel->getProperties()->setCategory('快速装箱模板');
			$phpexcel->setActiveSheetIndex(0);
			$phpexcel->getActiveSheet()->setTitle('装箱清单');
			$phpexcel->getDefaultStyle()->getFont()->setName('宋体');
			
			$phpexcel->getActiveSheet()->getStyle('A1:I1')->getFont()->setBold(true);
			$phpexcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
			$phpexcel->getActiveSheet()->setCellValue('A1', '装箱序号')->getColumnDimension('A')->setWidth(10);
			$phpexcel->getActiveSheet()->setCellValue('B1', 'SKU')->getColumnDimension('B')->setWidth(10);
			$phpexcel->getActiveSheet()->setCellvalue('C1', '装箱数量')->getColumnDimension('C')->setWidth(10);
			$phpexcel->getActiveSheet()->setCellvalue('D1', '实际追踪号')->getColumnDimension('D')->setWidth(15);
			$i = 2;
			$key = array_rand($ids, 1);
			foreach ($product as $p)
			{
				$phpexcel->getActiveSheet()->setCellValue('A'.$i, $ids[$key]);
				$phpexcel->getActiveSheet()->getCell('B'.$i)->setValueExplicit($p['number'], PHPExcel_Cell_DataType::TYPE_STRING);
				$phpexcel->getActiveSheet()->setCellValue('C'.$i, $p['actual_quantity']);
				$phpexcel->getActiveSheet()->setCellValue('D'.$i, '');
				$i++;
			}
			$writer = new PHPExcel_Writer_Excel5($phpexcel);
			header("Content-Type: application/vnd.ms-execl");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header('Content-Disposition:inline;filename=UploadPackingList.xls');
			header("Content-Transfer-Encoding: binary");
			header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
			header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Pragma: no-cache");
			$writer->save('php://output');
		}
	}
	
	function actionOutputDFProductTpl()
	{
		$this->_view['title'] = '导出达方产品资料模板';
		if (isset($_GET['ids']))
		{
			$ids = explode(',', $_GET['ids']);
			$product = Purchase_Order_Item::find('purchase_order_item.purchase_order_id in (?)', $ids)
				->joinLeft('product_basic', 'product_basic.*', 'purchase_order_item.product_basic_id=product_basic.id')
				->asArray()->getAll();
			include Q::ini('custom_system/lib_dir').'PHPExcel.php';
			$phpexcel = new PHPExcel();
			$phpexcel->getProperties()->setCreator(Q::ini('custom_system/system_name') . Q::ini('custom_system/version'));
			$phpexcel->getProperties()->setLastModifiedBy(Q::ini('custom_system/system_name') . Q::ini('custom_system/version'));
			$phpexcel->getProperties()->setTitle('DF仓产品资料');
			$phpexcel->getProperties()->setSubject('DF仓产品资料表');
			$phpexcel->getProperties()->setDescription('DF仓产品资料表-运营系统');
			$phpexcel->getProperties()->setKeywords('DF仓产品资料表');
			$phpexcel->getProperties()->setCategory('DF仓产品资料表');
			$phpexcel->setActiveSheetIndex(0);
			$phpexcel->getActiveSheet()->setTitle('产品信息（客户）');
			$phpexcel->getActiveSheet()->getStyle('A1:I1')->getFont()->setBold(true);
			$phpexcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
			$phpexcel->getActiveSheet()->setCellValue('A1', 'SKU')->getColumnDimension('A')->setWidth(10);
			$phpexcel->getActiveSheet()->setCellValue('B1', '英文名称')->getColumnDimension('B')->setWidth(10);
			$phpexcel->getActiveSheet()->setCellvalue('C1', '中文名称')->getColumnDimension('C')->setWidth(10);
			$phpexcel->getActiveSheet()->setCellvalue('D1', '仓储申报价值(RMB)')->getColumnDimension('D')->setWidth(25);
			$phpexcel->getActiveSheet()->setCellValue('E1', '是否带物流包装')->getColumnDimension('E')->setWidth(20);
			$phpexcel->getActiveSheet()->setCellValue('F1', '申报品名')->getColumnDimension('F')->setWidth(10);
			$phpexcel->getActiveSheet()->setCellValue('G1', '申报币种')->getColumnDimension('G')->setWidth(10);
			$phpexcel->getActiveSheet()->setCellValue('H1', '运输申报价值')->getColumnDimension('H')->setWidth(15);
			$phpexcel->getActiveSheet()->setCellValue('I1', '海关编码')->getColumnDimension('I')->setWidth(10);
			$i = 2;
			foreach ($product as $p)
			{
				$phpexcel->getActiveSheet()->getCell('A'.$i)->setValueExplicit($p['number'], PHPExcel_Cell_DataType::TYPE_STRING);
				$phpexcel->getActiveSheet()->setCellValue('B'.$i, $p['declared_name_en']);
				$phpexcel->getActiveSheet()->setCellValue('C'.$i, $p['declared_name_cn']);
				$phpexcel->getActiveSheet()->setCellValue('D'.$i, $p['declared_value']);
				$phpexcel->getActiveSheet()->setCellValue('E'.$i, '');
				$phpexcel->getActiveSheet()->setCellValue('F'.$i, '');
				$phpexcel->getActiveSheet()->setCellValue('G'.$i, '');
				$phpexcel->getActiveSheet()->setCellValue('H'.$i, '');
				$phpexcel->getActiveSheet()->setCellValue('I'.$i, '');
				$i++;
			}
			$writer = new PHPExcel_Writer_Excel5($phpexcel);
			header("Content-Type: application/vnd.ms-execl");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header('Content-Disposition:inline;filename=UploadProducts_Lite.xls');
			header("Content-Transfer-Encoding: binary");
			header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
			header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Pragma: no-cache");
			$writer->save('php://output');
		}
	}
	
	function actionUpdateBudgetStorageTime()
	{
		$this->_view['title'] = '更新预计入库时间';
		if ($this->_context->isPOST() && $_POST['id'] && $_POST['budget_storage_time'])
		{
			$id = explode(',', $_POST['id']);
			$message = '';
			foreach ($id as $i)
			{
				$purchase_order = Purchase_Order::find('id =?', $i)->asArray()->getOne();
				if ($purchase_order['warehouse_id'] != Warehouse::getDefaultWarehouseId())
				{
					if ($purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/send/value'))
					{
						QDB::getConn()->execute('update purchase_order set budget_storage_time = \'' . $_POST['budget_storage_time'] . '\' where id in (' . $_POST['id'] . ')');
					}
					else
					{
						$message .= $purchase_order['number'] . '不是已发送状态' . "\n";
					}
				}
				else
				{
					$message .= $purchase_order['number'] . '不是海外仓订单' . "\n";
				}
			}
			if ($message == '')
			{
				return $this->_redirectMessage('更新预计入库日期成功', '正在返回...', $_SERVER['HTTP_REFERER'], SUCCESS);
			}
			else
			{
				return $this->_redirectMessage('更新预计入库日期部分失败', $message, $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
	}

	function actionActualQuantityEdit()
	{
		$this->_view['title'] = '实际数编辑';
		$material = Product_Material::find()->asArray()->getAll();
		$this->_view['material'] = $material;
		$url_arr = Helper_BSS_Normal::buildCondition();
		if ($url_arr)
		{
			$purchase_order = Purchase_Order::find('purchase_order.id =?', $url_arr['id'])
				->joinLeft('user', 'name as purchase_user_name', 'user.id = purchase_order.purchase_user_id')
				->joinLeft('warehouse', 'warehouse.name as warehouse_name', 'warehouse.id=purchase_order.warehouse_id')
				->asArray()->getOne();
			$where = 'purchase_order_item.purchase_order_id=' . $url_arr['id'];
			$item = Purchase_Order_Item::find($where)
				->joinLeft('product_basic', 'number as product_number, name as product_name, weight, declared_value, declared_name_cn, declared_name_en', 'product_basic.id=purchase_order_item.product_basic_id')
				->joinLeft('product_warehouse', 'id as product_warehouse_id, actual_quantity as product_warehouse_actual_quantity, shelf_position, product_feature, tag', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=' . $purchase_order['warehouse_id'])
				->joinLeft('product_material', 'id as product_material_id, number as material_number, name as material_name', 'product_material.id=product_warehouse.product_material_id')
				->order('product_basic.number asc')->asArray()->getAll();
			Helper_BSS_Normal::getProductImgUrl($item, 'product_number');
			$this->_view['purchase_order'] = $purchase_order;
			$this->_view['item'] = $item;
		}
	}

	function actionActualQuantityEditSave()
	{
		$this->_view['title'] = '实际数编辑（保存）';
		$message = '';
		foreach ($_REQUEST['item'] as $k => $i)
		{
			$purchase_actual_quantity = $i['actual_quantity'];
			$purchase_order_item = Purchase_Order_Item::find('id=?', $k)->getOne();
			if ($purchase_order_item && empty($purchase_order_item['audit_flag']))
			{
				if ($purchase_actual_quantity <= $purchase_order_item['budget_quantity'])
				{
					$purchase_order = Purchase_Order::find('id=?', $purchase_order_item['purchase_order_id'])->asArray()->getOne();
					if ($purchase_order['type'] != Q::ini('custom_flag/purchase_order_type/drawback/value'))
					{
						if ($purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/arrived/value') || $purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/partial_storaged/value'))
						{
							Product_Warehouse::purchaseActualQuantityDecrease(0, $purchase_order_item['product_basic_id'], $purchase_order['warehouse_id'], (int)$purchase_order_item['actual_quantity']);
							Product_Warehouse::purchaseActualQuantityIncrease(0, $purchase_order_item['product_basic_id'], $purchase_order['warehouse_id'], (int)$purchase_actual_quantity);
						}
						if ($purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/purchased/value') || $purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/arrived/value') || $purchase_order['status'] == Q::ini('custom_flag/purchase_order_status/partial_storaged/value'))
						{
							Product_Warehouse::purchaseQuantityDecrease(0, $purchase_order_item['product_basic_id'], $purchase_order['warehouse_id'], (int)$purchase_order_item['actual_quantity']);
						}
						$purchase_order_item->actual_quantity = (int)($purchase_actual_quantity);
						$purchase_order_item->save();
						Product_Warehouse::purchaseQuantityIncrease(0, $purchase_order_item['product_basic_id'], $purchase_order['warehouse_id'], (int)$purchase_order_item['actual_quantity']);
						Purchase_Order::updateOrder($purchase_order['id']);
					}
				}
				else
				{
					$message .= $i['product_number'] . " 实际数不能大于预计数\n";
				}
			}
			else
			{
				$message .= $i['product_number'] . " item不存在或者已审核\n";
			}
		}
		if ($message)
		{
			return $this->_redirectMessage('保存部分失败', $message, url('Storage::DFOverseas/Detail', array('id'=>$_REQUEST['purchase_order_id'], 'show_all'=>1, 'operate'=>1)), PARTIAL_FAILURE);
		}
		else
		{
			return $this->_redirectMessage('保存成功', '正在返回..', url('Storage::DFOverseas/Detail', array('id'=>$_REQUEST['purchase_order_id'], 'show_all'=>1, 'operate'=>1)), SUCCESS);
		}
	}
	
	function actionInfoEdit()
	{
		$this->_view['title'] = '信息编辑';
		$material = Product_Material::find()->asArray()->getAll();
		$this->_view['material'] = $material;
		$url_arr = Helper_BSS_Normal::buildCondition();
		if ($url_arr)
		{
			$purchase_order = Purchase_Order::find('purchase_order.id =?', $url_arr['id'])
				->joinLeft('user', 'name as purchase_user_name', 'user.id = purchase_order.purchase_user_id')
				->joinLeft('warehouse', 'warehouse.name as warehouse_name', 'warehouse.id=purchase_order.warehouse_id')
				->asArray()->getOne();
			$where = 'purchase_order_item.purchase_order_id=' . $url_arr['id'];
			$item = Purchase_Order_Item::find($where)
				->joinLeft('product_basic', 'number as product_number, name as product_name, weight, declared_value, declared_name_cn, declared_name_en', 'product_basic.id=purchase_order_item.product_basic_id')
				->joinLeft('product_warehouse', 'id as product_warehouse_id, actual_quantity as product_warehouse_actual_quantity, shelf_position, product_feature, tag', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=' . $purchase_order['warehouse_id'])
				->joinLeft('product_material', 'id as product_material_id, number as material_number, name as material_name', 'product_material.id=product_warehouse.product_material_id')
				->order('product_basic.number asc')->asArray()->getAll();
			Helper_BSS_Normal::getProductImgUrl($item, 'product_number');
			$this->_view['purchase_order'] = $purchase_order;
			$this->_view['item'] = $item;
		}
	}
	
	function actionInfoEditSave()
	{
		$this->_view['title'] = '信息编辑（保存）';
		foreach ($_REQUEST['item'] as $k => $i)
		{
			$check_in_db = Product_Warehouse::find('id=?', $i['product_warehouse_id'])->getOne();
			if ($check_in_db['id'])
			{
				$check_in_db->product_material_id = $i['product_material_id'];
				$check_in_db->shelf_position = $i['shelf_position'];
				$check_in_db->product_feature = $i['product_feature'];
				$check_in_db->tag = $i['tag'];
				$check_in_db->save();
			}
		}
		return $this->_redirectMessage('保存成功', '正在返回..', url('Storage::DFOverseas/Detail', array('id'=>$_REQUEST['purchase_order_id'], 'show_all'=>1, 'operate'=>1)), SUCCESS);
	}
	
	function actionUpdateLspNumber()
	{
		$this->_view['title'] = '更新达方单号';
		if ($this->_context->isPOST())
		{
			if (! empty($_POST['sales_order_id']) && ! empty(trim($_POST['lsp_number'])))
			{
				$check_in_db = Sales_Order::find('id=?', $_POST['sales_order_id'])->getOne();
				if ($check_in_db['id'])
				{
					if ($check_in_db['synchronous_flag'] == Q::ini('custom_flag/sales_order_synchronous_flag/DF/value'))
					{
						$check_in_db->lsp_number = trim($_POST['lsp_number']);
						$check_in_db->save();
						return $this->_redirectMessage('更新成功', '正在返回..', $_SERVER['HTTP_REFERER'], SUCCESS);
					}
					else
					{
						return $this->_redirectMessage('更新失败', '请检查该订单是否同步过达方仓', $_SERVER['HTTP_REFERER'], FAILURE);
					}
				}
				else
				{
					return $this->_redirectMessage('更新失败', '不存在该订单', $_SERVER['HTTP_REFERER'], FAILURE);
				}
			}
			else
			{
				return $this->_redirectMessage('更新失败', '提交方式有误或缺失参数', $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
		return $this->_redirectMessage('操作失败', '提交方式错误', $_SERVER['HTTP_REFERER'], FAILURE);
	}
}